package org.raymond.iworks.study.basic.thread.completablefuture;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
public class Demo2 {
    public static void main(String[] args) {
        test1();
    }
    public static void test1(){
        ThreadPoolExecutor te = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MICROSECONDS, new LinkedBlockingQueue<>());

        CompletableFuture<Map<String, Object>> f1 = CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, Object> map = new HashMap<>();
            map.put("num", 1);
            log.info("f1 模拟执行RPC");
            return map;
        });

        CompletableFuture<Map<String, Object>> f2 = CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, Object> map = new HashMap<>();
            map.put("num", 3);
            log.info("f2 模拟执行RPC");
            return map;
        });

        CompletableFuture<Map<String, Object>> f3 = CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, Object> map = new HashMap<>();
            map.put("num", 5);
            log.info("f3 模拟执行RPC");
            return map;
        });
        CompletableFuture.allOf(f1, f2, f3).completeAsync(()->{
            try {
                Map<String, Object> m1 = f1.get();
                Map<String, Object> m2 = f2.get();
                Map<String, Object> m3 = f3.get();

                Object r1 = m1.get("num");
                Object r2 = m2.get("num");
                Object r3 = m3.get("num");
                log.info("{}, {}, {}", r1, r2, r3);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }, te);

        te.shutdown();
    }
}
